package org.batatasframework.support.charts;

import java.text.DecimalFormat;
import java.util.Map;

import cn.bonoon.kernel.util.StringHelper;

public abstract class ChartResultParser {

	protected final DecimalFormat format;

	protected ChartResultParser(DecimalFormat format){
		this.format = format;
	}
	
	/** 这里主要是进行数据的格式化处理，如果需要的话。 */
	public Object[] parse(Map<String, Number> sum){
		if(null != format){
			int i = 0;
			Object[] rs = new Object[sum.size()];
			for(Number num : sum.values()){
				rs[i++] = format.format(num);
			}
			return rs;
		}
		
		return sum.values().toArray();
	}
	
	public final static ChartResultParser numberParser(){
		return new ChartResultNumberParser();
	}

	public final static ChartResultParser numberParser(DecimalFormat format){
		return new ChartResultNumberParser(format);
	}

	public final static ChartResultParser decimalParser(){
		return new ChartResultDecimalParser();
	}

	public final static ChartResultParser decimalParser(DecimalFormat format){
		return new ChartResultDecimalParser(format);
	}
	
	public abstract Number add(Number one, Number two);
	public abstract Number add(Number one, Number...more);
	
	public Number add(Number one, Object[] items, int index){
		return add(one, (Number)items[index]);
	}
	
	public Number add(Number one, Object item){
		return add(one, (Number)item);
	}

	private final static class ChartResultNumberParser extends ChartResultParser{

		protected ChartResultNumberParser(DecimalFormat format) {
			super(format);
		}

		protected ChartResultNumberParser() {
			super(null);
		}

		@Override
		public Number add(Number one, Number two) {
			if(null == two) return one;
			if(null == one) return two;
			//如果是Double类型保留两位小数
			if(one instanceof Double || two instanceof Double){
				DecimalFormat    df   = new DecimalFormat("#.00");  
				return StringHelper.todouble(df.format(one.doubleValue() + two.doubleValue()));
			}
			else{
				return one.longValue() + two.longValue();
			}
		}

		@Override
		public Number add(Number one, Number... more) {
			long val = one.longValue();
			for(Number m : more){
				val += m.longValue();
			}
			return val;
		}
		
	}

	private final static class ChartResultDecimalParser extends ChartResultParser{

		protected ChartResultDecimalParser(DecimalFormat format) {
			super(format);
		}

		protected ChartResultDecimalParser() {
			super(null);
		}

		@Override
		public Number add(Number one, Number two) {
			if(null == one)return two; 
			if(null == two)return one;
			return one.doubleValue() + two.doubleValue();
		}

		@Override
		public Number add(Number one, Number... more) {
			double val = one.doubleValue();
			for(Number m : more){
				val += m.doubleValue();
			}
			return val;
		}
		
	}
}
